<?php

class alipay_app {

    private $config;

    public function __construct($payment_info = array(), $order_info = array()) {
        if (!empty($payment_info)) {
            $this->config = array(
                //应用ID,您的APPID。
                'app_id' => $payment_info['payment_config']['alipay_appid'],
                //商户私钥
                'merchant_private_key' => $payment_info['payment_config']['private_key'],
                //异步通知地址
                'notify_url' => str_replace('/index.php', '', HOME_SITE_URL) . '/payment/alipay_app_notify.html', //通知URL,
                //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
                'alipay_public_key' => $payment_info['payment_config']['public_key'],
            );
        }
    }
    function get_payform($param) {

        require_once PLUGINS_PATH . '/payments/alipay_app/AopClient.php';
        $aop = new \AopClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = $this->config['app_id'];
        $aop->rsaPrivateKey = $this->config['merchant_private_key'];
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = $this->config['alipay_public_key'];
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay

        require_once PLUGINS_PATH . '/payments/alipay_app/request/AlipayTradeAppPayRequest.php';
        $request = new \AlipayTradeAppPayRequest();
        $bizcontent = "{\"body\":\"{$param['order_type']}\","
                . "\"subject\":\"{$param['subject']}\","
                . "\"out_trade_no\":\"{$param['order_type']}-{$param['pay_sn']}\","
                . "\"total_amount\":\"{$param['api_pay_amount']}\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
        
        $request->setNotifyUrl($this->config['notify_url']);
        $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);

//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
//        echo htmlspecialchars($response); //就是orderString 可以直接给客户端请求，无需再做处理。

        ds_json_encode(10000,'',array('content'=>$response));
    }

    function verify_notify() {

        require_once PLUGINS_PATH . '/payments/alipay_app/AopClient.php';
        $aop = new \AopClient;
        \think\Log::error("支付回调参数".json_encode($_POST));
        $aop->alipayrsaPublicKey = $this->config['alipay_public_key'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if ($flag) {
	        $a_trade_no=input('param.out_trade_no');
	        if(strpos($a_trade_no, "-") !== false){
		        $out_trade_no = explode('-', $a_trade_no);
		        $out_trade_no = $out_trade_no['1'];
	        }else{
		        $out_trade_no = $a_trade_no;
	        }

            $notify_result = array(
                'out_trade_no' => $out_trade_no, #商户订单号
                'trade_no' => $_POST['trade_no'], #交易凭据单号
                'total_fee' => $_POST["total_amount"], #涉及金额
                'order_type' => input('param.body'),
                'trade_status' => '1',
            );
        } else {
            $notify_result = array(
                'trade_status' => '0',
            );
        }
        return $notify_result;
    }


	/**
	 * 原路退款
	 */
	public function trade_refund($order_info,$refund_amount)
	{
		//构造参数
		require_once PLUGINS_PATH . '/payments/alipay/buildermodel/AlipayTradeRefundContentBuilder.php';
		require_once PLUGINS_PATH . '/payments/alipay/service/AlipayTradeService.php';
		$RequestBuilder = new AlipayTradeRefundContentBuilder();

		//setOutTradeNo  setOutRequestNo
		$RequestBuilder->setTradeNo($order_info['trade_no']);
		$RequestBuilder->setRefundAmount($refund_amount);
		$RequestBuilder->setRefundReason('订单退款');
		$RequestBuilder->setOutRequestNo($order_info['out_request_no']);//支付宝部分退款必传唯一的标识一次退款请求号

		$aop = new AlipayTradeService($this->config);
		$response = $aop->Refund($RequestBuilder);

		if($response->code == 10000){
			return ds_callback(TRUE, $response->msg);
		}else{
			return ds_callback(FALSE, $response->msg);
		}

		/*
object(stdClass)#41 (10) {
  ["code"] => string(5) "10000"
  ["msg"] => string(7) "Success"
  ["buyer_logon_id"] => string(14) "l***@126.com"
  ["buyer_user_id"] => string(16) "2088002237181934"
  ["fund_change"] => string(1) "Y"
  ["gmt_refund_pay"] => string(19) "2019-09-19 16:06:01"
  ["out_trade_no"] => string(31) "real_order-19091911525456613013"
  ["refund_fee"] => string(4) "0.01"
  ["send_back_fee"] => string(4) "0.00"
  ["trade_no"] => string(28) "2019091922001481930549025169"
}
		 */
	}

	/**
	 * 单笔转账支付宝账号
	 * @param $param
	 *
	 */
	public function trans_toaccount_transfer($param)
	{
		//if(floatval($param['amount'])<0.1){
		//	return ds_callback(FALSE, "转账金额必须大于0.1元");
		//}
		require_once PLUGINS_PATH . '/payments/alipay_app/AopClient.php';
		$aop = new \AopClient();
		$aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
		$aop->appId = $this->config['app_id'];
		$aop->rsaPrivateKey = $this->config['merchant_private_key'];
		$aop->format = "json";
		$aop->charset = "UTF-8";
		$aop->signType = "RSA2";
		$aop->alipayrsaPublicKey = $this->config['alipay_public_key'];

		require_once PLUGINS_PATH . '/payments/alipay_app/request/AlipayFundTransToaccountTransferRequest.php';
		$request =new  \AlipayFundTransToaccountTransferRequest();
		$arr['out_biz_no'] = $param['out_biz_no'];
		$arr['payee_type'] ="ALIPAY_LOGONID";
		$arr['payee_account'] = $param['payee_account'];//收款方账户
		$arr['amount'] = floatval($param['amount']);//转账金额
		if(isset($param['remark']) && !empty($param['remark'])){
			$arr['remark']=$param['remark'];
		}
		$bizcontent = json_encode($arr);

		\think\Log::error("转账参数".$bizcontent);
		//$request->setNotifyUrl($this->config['notify_url']);
		$request->setBizContent($bizcontent);
		//这里和普通的接口调用不同，使用的是sdkExecute
		$response = $aop->execute($request);
		$response=$response->alipay_fund_trans_toaccount_transfer_response;
		\think\Log::error("转账参数测试". $response->msg);
		if($response->code == 10000){
			return ds_callback(TRUE, $response->msg,$response->order_id);
		}else{
			return ds_callback(FALSE, $response->msg);
		}
	}

	/**
	 * 统一下单转账
	 * @param $param
	 * @return multitype
	 */
	public function fund_trans_uni_transfer($param)
	{
		//if(floatval($param['amount'])<0.1){
		//	return ds_callback(FALSE, "转账金额必须大于0.1元");
		//}
		require_once PLUGINS_PATH . '/payments/alipay_app/AopClient.php';
		$aop = new \AopClient();
		$aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
		$aop->appId = $this->config['app_id'];
		$aop->rsaPrivateKey = $this->config['merchant_private_key'];
		$aop->format = "json";
		$aop->charset = "UTF-8";
		$aop->signType = "RSA2";
		$aop->alipayrsaPublicKey = $this->config['alipay_public_key'];

		require_once PLUGINS_PATH . '/payments/alipay_app/request/AlipayFundTransUniTransferRequest.php';
		$request =new  \AlipayFundTransUniTransferRequest();
		$arr['out_biz_no'] = $param['out_biz_no'];
		$arr['product_code'] ="TRANS_ACCOUNT_NO_PWD";
		$arr['payee_account'] = $param['payee_account'];//收款方账户
		$arr['trans_amount'] = floatval($param['amount']);//转账金额

		if(isset($param['title']) && !empty($param['title'])){
			$arr['order_title']=$param['title'];
		}
		if(isset($param['remark']) && !empty($param['remark'])){
			$arr['remark']=$param['remark'];
		}
		$bizcontent = json_encode($arr);


		//$request->setNotifyUrl($this->config['notify_url']);
		$request->setBizContent($bizcontent);
		//这里和普通的接口调用不同，使用的是sdkExecute
		$response = $aop->execute($request);
		var_dump($response);exit;
		$response=$response->alipay_fund_trans_toaccount_transfer_response;

		\think\Log::error("转账参数测试". $response->msg);
		if($response->code == 10000){
			return ds_callback(TRUE, $response->msg,$response->order_id);
		}else{
			return ds_callback(FALSE, $response->msg);
		}
	}
}

?>
